<?php
	defined('RUN') or die('No access');
	
	class CategoryModel
	{
	    public function getCategories($parent_id = 0)
		{
			return Model::getDataSql("SELECT * FROM `categories` WHERE parent_id = '" . (int)$parent_id . "' AND status = 1 ORDER BY sort ASC");
		}
        
        public function getCategoriesAdm($parent_id = 0)
		{
			return Model::getDataSql("SELECT * FROM `categories` WHERE parent_id = '" . (int)$parent_id . "' ORDER BY sort ASC");
		}

		public function getById($id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			$cat = Model::getData('categories', '*', $condition);

			if ($cat)
				return $cat[0];

			return FALSE;
		}
        
        public function getCategoriesAll($parent_id = 0) {
			$category_data = array();
		
			$rows =  Model::getDataSql("SELECT * FROM `categories` WHERE parent_id = '" . (int)$parent_id . "' ORDER BY sort, name ASC");
		
			foreach ($rows  as $result) {
				$category_data[] = array(
					'id'     => $result['id'],
					'name'   => $this->getPath($result['id']),
                    'parent_id' => $result['parent_id'],
					'status' => $result['status'],
					'sort'   => $result['sort']
				);
			
				$category_data = array_merge($category_data, $this->getCategoriesAll($result['id']));
			}	
	
    		return $category_data;
    	}
    	
    	public function getPath($category_id) {
    		$rows =  Model::getDataSql("SELECT name, parent_id FROM `categories` WHERE id = '" . (int)$category_id . "'  ORDER BY sort, name ASC");
    		
    		if ($rows[0]['parent_id']) {
    			return $this->getPath($rows[0]['parent_id']) . ' > ' . $rows[0]['name'];
    		} else {
    			return $rows[0]['name'];
    		}
    	}

		public function add($category)
		{
			return Model::insertData('categories', $category);
		}

		public function update($category, $id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);
			
			return Model::updateData('categories', $category, $condition);
		}

		public function delete($id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			return Model::deleteData('categories', $condition);
		}
	}
